﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using LJF.Models;
using LJF.Models.Models;
using LJF.MSSQL;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace LJF.ManageSYS.Controllers
{
    [Route("api/[controller]/[action]")]
    public class MenusController : BaseController
    {
        ManageSys_DATAContext dataMD;
        public MenusController(ManageSys_DATAContext _dataMD)
        {
            dataMD = _dataMD;
        }

        [HttpGet]
        public ResponseData GetMenuList()
        {
            List<XtMenu> menus = dataMD.XtMenu.OrderBy(p => p.Pid).OrderBy(p => p.Sort).ToList();
            return Success(menus, menus.Count);
        }

        [HttpPost]
        public ResponseData Add(XtMenu menu)
        {
            int num = DbHelper.SqlDSN.ExecuteSql($"insert into XT_Menu(Title,Pid,Href,Icon,Sort) values('{menu.Title}','{menu.Pid}','{menu.Href}','{menu.Icon}','{menu.Sort}')");
            if (num > 0)
            {
                return Success("添加成功！");
            }
            else
            {
                return Fail("添加失败！");
            }
        }

        [HttpPost]
        public ResponseData Update(XtMenu menu)
        {
            int num = DbHelper.SqlDSN.ExecuteSql($"update XT_Menu set Title='{menu.Title}',Icon='{menu.Icon}',Href='{menu.Href}',Sort='{menu.Sort}' where id='{menu.Id}'");
            if (num > 0)
            {
                return Success("修改成功！");
            }
            else
            {
                return Fail("修改失败！");
            }
        }

        [HttpPost]
        public ResponseData Delete(string id)
        {
            int childList = dataMD.XtMenu.Count(p => p.Pid == int.Parse(id));
            if (childList > 0)
            {
                return Fail("该菜单下存在子级，不允许删除！");
            }
            int num = DbHelper.SqlDSN.ExecuteSql($"delete XT_Menu where ID='{id}'");
            if (num > 0)
            {
                return Success("删除成功！");
            }
            else
            {
                return Fail("删除失败！");
            }
        }
    }
}